<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :close-on-press-escape="dialogCloseOnEsc"
    @open="handleDialogOpen"
    @close="handleDialogClose"
    max-height="500"
    width="1000"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="模板编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入模板编码" />
      </el-form-item>
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="模板类型" prop="type">
        <el-radio-group v-model="formData.type" @change="handleTypeChange">
          <el-radio v-for="dict in system_mail_template_type" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="模板标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入模板标题，支持 {param1} 格式模板参数"
        />
      </el-form-item>
      <el-form-item
        v-if="formData.type === SystemMailTemplateTypeEnum.Placeholder"
        label="模板内容"
        prop="content"
      >
        <Editor
          ref="placeholderEditorRef"
          v-model="formData.content"
          placeholder="请输入内容，支持 {param1} 格式模板参数"
          @fullscreen="handleWangEditorFullscreen"
          height="160px"
        />
      </el-form-item>
      <el-form-item
        v-if="formData.type === SystemMailTemplateTypeEnum.Freemarker"
        prop="content"
        class="editor-container"
        :class="{ fullscreen: isAceEditorFullscreen }"
      >
        <template #label>
          <div @dblclick="toggleAceEditorFullscreen">
            <Tooltip message="双击标签：全屏切换" title="模板内容" />
          </div>
        </template>
        <v-ace-editor
          v-model:value="formData.content"
          lang="ftl"
          theme="chrome"
          placeholder="请输入或粘贴模板内容"
          :options="{ fontSize: 13, tabSize: 2, useSoftTabs: true, showPrintMargin: false }"
          style="width: 100%; height: 100%"
        />
      </el-form-item>
      <el-form-item label="发送邮箱账号" prop="accountId">
        <el-select
          v-model="formData.accountId"
          :empty-values="[0, '', null, undefined]"
          :value-on-clear="0"
          clearable
          placeholder="请选择邮箱账号"
        >
          <el-option
            v-for="account in accountList"
            :key="account.id"
            :value="account.id"
            :label="account.mail"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送人名称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入发送人名称" />
      </el-form-item>
      <el-form-item label="开启状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in common_enable_status" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { MailTemplateApi, MailTemplateVO } from '@/api/system/mail/mail_template'
import { MailAccountApi, MailAccountVO } from '@/api/system/mail/mail_account'
import { SystemMailTemplateTypeEnum } from '@/utils/constants'
import { FormRules } from 'element-plus'
import { VAceEditor } from 'vue3-ace-editor'
import 'ace-builds/src-noconflict/mode-ftl'
import 'ace-builds/src-noconflict/theme-chrome'
// import workerJsonUrl from 'ace-builds/src-noconflict/worker-html?url'
// ace.config.setModuleUrl('ace/mode/ftl_worker', workerJsonUrl)
import { Editor } from '@/components/Editor'
import { isHtmlHasContent } from '@/utils/lizard'

defineOptions({ name: 'SystemMailTemplateForm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { system_mail_template_type } = useDict(DICT_TYPE.system_mail_template_type)
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)

const dialogVisible = ref(false) // dialog是否展示
const dialogCloseOnEsc = ref(true)
const dialogTitle = ref('') // dialog标题
const formLoading = ref(false) // 表单加载中标记，1. 修改时的数据加载，2. 提交的按钮禁用
const formType = ref('') // 表单类型，新增：create，修改：update
const formDataObj = {
  id: undefined,
  name: undefined,
  code: undefined,
  type: SystemMailTemplateTypeEnum.Placeholder,
  accountId: undefined,
  nickname: undefined,
  title: undefined,
  content: '',
  status: undefined,
  remark: undefined
}
const formData = ref({ ...formDataObj })
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '模板编码不能为空', trigger: 'blur' }],
  accountId: [{ required: true, message: '邮箱账号不能为空', trigger: 'change' }, not_zero],
  title: [{ required: true, message: '模板标题不能为空', trigger: 'blur' }],
  content: [
    { required: true, message: '模板内容不能为空', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (!isHtmlHasContent(value)) {
          callback(new Error('模板内容不能为空'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const accountList = ref<MailAccountVO[]>([]) // 邮箱账号列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MailTemplateApi.getMailTemplate(id)
    } finally {
      formLoading.value = false
    }
  }
  accountList.value = await MailAccountApi.getMailAccountSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  if (await formValidate(formRef)) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MailTemplateVO
    if (formType.value === 'create') {
      await MailTemplateApi.createMailTemplate(data)
      message.success(t('common.createSuccess'))
    } else {
      await MailTemplateApi.updateMailTemplate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

let placeholderContent = ''
let freemarkerContent = ''
const handleTypeChange = (type: string) => {
  switch (type) {
    case SystemMailTemplateTypeEnum.Placeholder:
      freemarkerContent = formData.value.content
      formData.value.content = placeholderContent
      break
    case SystemMailTemplateTypeEnum.Freemarker:
      placeholderContent = formData.value.content
      formData.value.content = freemarkerContent
      break
  }
}

const placeholderEditorRef = ref<InstanceType<typeof Editor>>()
const isWangEditorFullscreen = ref(false)
const handleWangEditorFullscreen = (fullscreen: boolean) => {
  isWangEditorFullscreen.value = fullscreen
  dialogCloseOnEsc.value = !isWangEditorFullscreen.value
}

const isAceEditorFullscreen = ref(false)
const toggleAceEditorFullscreen = () => {
  isAceEditorFullscreen.value = !isAceEditorFullscreen.value
  dialogCloseOnEsc.value = !isAceEditorFullscreen.value
}

/** 重置表单 */
const resetForm = () => {
  formData.value = { ...formDataObj }
  formRef.value?.resetFields()
  placeholderContent = ''
  freemarkerContent = ''
}

const handleEscKey = async (event) => {
  if (event.key === 'Escape') {
    if (isAceEditorFullscreen.value) {
      // 如果 editor-container 处于全屏模式，则退出全屏
      toggleAceEditorFullscreen()
      event.stopPropagation()
    } else if (isWangEditorFullscreen.value) {
      // 如果 wangeditor 处于全屏模式，则退出全屏
      ;(await placeholderEditorRef.value?.getEditorRef())?.unFullScreen()
      event.stopPropagation()
    }
  }
}

const handleDialogOpen = () => {
  document.addEventListener('keydown', handleEscKey)
}

const handleDialogClose = () => {
  isAceEditorFullscreen.value = false
  isWangEditorFullscreen.value = false
  document.removeEventListener('keydown', handleEscKey)
}
</script>

<style scoped lang="scss">
.editor-container {
  height: 160px;
}

/* 全屏模式 */
.editor-container.fullscreen {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 1000 !important;
  width: 100vw !important;
  height: 100vh !important;
  max-width: none !important;
  max-height: none !important;
  background: white !important;
}
</style>
